<?php

namespace App\Admin\Controllers;

use App\Admin\Tools\sureOrder;
use App\Exceptions\Interfaces\OrderServiceException;
use App\Exceptions\InvalidRequestException;


;
use App\Interfaces\Express;
use App\Interfaces\OrderService;
use App\Jobs\DisTributeSettlement;
use App\OrderPay;

use App\Repositories\UserRepository;
use App\User;
use App\UserMoneyLog;
use Barryvdh\DomPDF\PDF;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Mpdf\Mpdf;
use Symfony\Component\Translation\Exception\InvalidResourceException;

class OrdersController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {

        return Admin::content(function (Content $content) {

            $content->header('订单列表');
            $content->description('订单列表');

            $content->body($this->grid(0));
        });
    }
    public function sureList(){
        return Admin::content(function (Content $content) {

            $content->header('待接单待发货订单');
            $content->description('待接单代发货订单');

            $content->body($this->grid(1));
        });
    }
    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($is_true)
    {
        return Admin::grid(OrderPay::class, function (Grid $grid) use($is_true){
            $grid->model()
                 ->leftJoin('order_pay_address', 'order_pay.address_id', '=', 'order_pay_address.id')
                ->join('users','users.id','=','order_pay.user_id')
                ->whereNotNull('order_pay.paid_at')
                ->select('users.team_leader','order_pay_address.*','order_pay.*')
                ->orderBy('order_pay.paid_at', 'desc');
            if($is_true==1){//待接单 代发货
                $grid->model()
                    ->whereIn('order_pay.ship_status',[OrderPay::SHIP_STATUS_PENDING,OrderPay::SHIP_STATUS_SURE_ORDER])
                    ->where('order_pay.refund_status','!=',OrderPay::REFUND_STATUS_APPLIED);
            }
            $grid->disableCreateButton();
            $grid->user_id('下单人')->display(function($value){
                $user= User::find($value);

                if($user){
                return 'id:'.$user->id.'</br>名称:'.$user->name;}else{
                    return '用户不存在';
                }
            });
            $grid->leader('分享人')->display(function($value){
                $user= User::find($this->user_id);

                if(isset($user->team_leader)){
                    $leader=User::find($user->team_leader);
                    return 'id:'.$leader->id.'</br>名称:'.$leader->name;
                }else{
                    return '无分享人';
                }
            });
          //  $grid->order_pay_id('ID')->sortable();
            $grid->pay_sn('流水号');
            $grid->pay_price('付款金额（包括余额支付）')->display(function($value){
                return $this->pay_balance+$value;
            });
            $grid->pay_balance('余额支付');
            $grid->total_money('订单金额');
            $grid->pay_type('支付方式')->display(function ($value) {
                if (isset(OrderPay::$payTypeMap[$value])) {
                    return OrderPay::$payTypeMap[$value];
                }
                return '余额支付';
            });

            $grid->consignee('收货人');
            $grid->mobile('手机号');
            $grid->ship_status('物流')->display(function ($value) {
                return OrderPay::$shipStatusMap[$value];
            });

            $grid->mail_no('物流面单号');
            $grid->refund_status('退款状态')->display(function ($value) {

                return OrderPay::$refundStatusMap[$value] ?? '未退款';
            });
            $grid->refund_time('退款时间')->display(function($value){
                return  $value ?? '';
            });
            $grid->paid_at('支付时间');
            $grid->create_time('下单时间');
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('<a class="btn btn-xs btn-primary" href="' . route('order.show', [$actions->getKey()]) . '">查看</a>');

            });

            //批量
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                    $batch->add('批量接单', new sureOrder(1));

                });
            });
            $grid->exporter(new \App\Admin\Export\OrderHanleExport());
            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                //收货人姓名
                $filter->like('consignee', '收货人姓名');
                //分享人Id
                $filter->equal('team_leader','分享人Id');
                // 在这里添加字段过滤器
                $filter->like('mobile', '手机号');
                $filter->like('pay_sn','流水订单号');
                //发货状态
                $shipStatusMap=[' '=>'全部'];
                $shipStatusMap=array_merge($shipStatusMap,OrderPay::$shipStatusMap);
                $filter->equal('ship_status', '发货状态')->select($shipStatusMap);
                //退款状态
                $refundStatusMap=[' '=>'全部'];
                $refundStatusMap=array_merge($refundStatusMap,OrderPay::$refundStatusMap);
                $filter->equal('refund_status', '退款状态')->select($refundStatusMap);
                //下单日期范围
                $filter->between('create_time', '下单时间')->datetime();

            });
        });
    }

    public function show(OrderPay $order)
    {
        return Admin::content(function (Content $content) use ($order) {
            $content->header('查看订单');
            // body 方法可以接受 Laravel 的视图作为参数
            $content->body(view('admin.orders.show', ['order' => $order]));
        });
    }

    public function sure(OrderPay $order, Request $request, Express $express)
    {

        if ($order->ship_status !== OrderPay::SHIP_STATUS_SURE_ORDER) {

            $error = new MessageBag([
                'title' => '确认失败',
                'message' => '不是确认订单阶段',
            ]);
            return redirect()->back()->with(compact('error'));
        }

        $print = $request->print;
        if ($print == 'on') {
            if ($order->express_no) {
                $error = new MessageBag([
                    'title' => '失败',
                    'message' => '快递单号已生成',
                ]);
                return redirect()->back()->with(compact('error'));
            }
            //生成订单
            $express = $express->creatExpress($order);
            //dd($express);
            if ($express['status'] != 1) {
                $error = new MessageBag([
                    'title' => '确认失败',
                    'message' => $express['msg'],
                ]);
                return redirect()->back()->with(compact('error'));
            } else {
                //
                $order->ship_status = OrderPay::SHIP_STATUS_DELIVERED;
                $order->express_no = $express['order_serial_no'];
                $order->express_company = '韵达物流';
                $order->mail_no = $express['mail_no'];
                $order->pdf_info = $express['pdf_info'];
                $order->save();
                $userRepository= new UserRepository();
                $userRepository->SendOrderNotice(User::find($order->user_id),$order);
                $userMoneyLog= UserMoneyLog::where('order_pay_id',$order->order_pay_id)->get();
                if($userMoneyLog->isNotEmpty()){
                    foreach ($userMoneyLog as $v){
                        if ($v->status!=1){
                            $this->dispatch(new DisTributeSettlement($v,10));
                        }

                    }
                }


                $success = new MessageBag(
                    [
                        'title' => '快递信息获取成功',
                        'message' => '点击查看快递模板信息',
                    ]
                );
                return redirect()->back()->with(compact('success'));
            }
        } else {

            $order->ship_status = OrderPay::SHIP_STATUS_PENDING;
            $order->save();

            $success = new MessageBag(
                [
                    'title' => '订单确认成功',
                    'message' => '订单确认成功',
                ]
            );
            return redirect()->back()->with(compact('success'));
        }
    }
    public function sureOrders(Request $request,Express $express){
        if($request->ids){
            $order=  OrderPay::find($request->ids);

            if (!$order->express_no) {

                $express = $express->creatExpress($order);

                if ($express['status'] != 1) {
                    $error = ['code'=>'error','message'=>$express['msg']];
                   return Response()->json($error);
                } else {
                    //
                    $order->ship_status = OrderPay::SHIP_STATUS_DELIVERED;
                    $order->express_no = $express['order_serial_no'];
                    $order->express_company = '韵达物流';
                    $order->mail_no = $express['mail_no'];
                    $order->pdf_info = $express['pdf_info'];
                    $order->save();
                    $user=User::find($order->user_id);
                    $userRepository= new UserRepository();
                    $userRepository->SendOrderNotice($user,$order);
                    $userMoneyLog= UserMoneyLog::where('order_pay_id',$order->order_pay_id)->get();
                    if($userMoneyLog->isNotEmpty()){
                        foreach ($userMoneyLog as $v){
                            if ($v->status!=1){
                                $this->dispatch(new DisTributeSettlement($v,10));
                            }
                        }
                    }
                    $success=['code'=>'success','message'=>$order->order_pay_id];
                    return Response()->json($success);
                }
            }else{
                $success=['code'=>'success','message'=>$order->order_pay_id];
                return Response()->json($success);
            }
        }else{
            return Response()->json(['code'=>'error','message'=>'订单已发放']);
        }
    }
    public function printExpress(OrderPay $order)
    {
     //   dd($order);

        //生成pdf

      /*  $pdf = \App::make('dompdf.wrapper');
        if (!is_dir(storage_path('/app/public/Pdf'))) {

            mkdir(storage_path('/app/public/Pdf'));
        }
       if (file_exists(storage_path('/app/public/Pdf/' . $order->pay_sn . '.pdf'))) {

            $pdfContent=file_get_contents(storage_path('/app/public/Pdf/' . $order->pay_sn . '.pdf'));
            return \Response::make($pdfContent)->header('Content-Type', 'application/pdf');
        }
        $pdf->loadView('admin.orders.pdf',['order'=>$order])->save(storage_path('/app/public/Pdf/' . $order->pay_sn . '.pdf'));
        return $pdf->stream();*/

      return view('admin.orders.pdf',compact('order'))
;
    }

    public function ship(OrderPay $order, Request $request)
    {
        // 判断当前订单是否已支付
        if (!$order->paid_at) {

            throw new InvalidRequestException('该订单未付款');

        }
        // 判断当前订单发货状态是否为未发货
        if ($order->ship_status !== OrderPay::SHIP_STATUS_PENDING) {
            throw new InvalidRequestException('该订单已发货');
        }
        // Laravel 5.5 之后 validate 方法可以返回校验过的值
        $data = $this->validate($request, [
            'express_company' => ['required'],
            'express_no' => ['required'],
        ], [], [
            'express_company' => '物流公司',
            'express_no' => '物流单号',
        ]);
        // 将订单发货状态改为已发货，并存入物流信息
        $order->ship_status = OrderPay::SHIP_STATUS_DELIVERED;
        $order->express_company = $request->express_company;
        $order->express_no = $request->express_no;
        $order->mail_no=$request->express_no;
        $order->save();
        $userRepository= new UserRepository();
        $userRepository->SendOrderNotice(User::find($order->user_id),$order);
        $userMoneyLog= UserMoneyLog::where('order_pay_id',$order->order_pay_id)->get();
        if($userMoneyLog->isNotEmpty()){
            foreach ($userMoneyLog as $v){
                if ($v->status!=1){
                    $this->dispatch(new DisTributeSettlement($v,10));
                }

            }
        }
        // 返回上一页
        return redirect()->back();
    }

    public function cancel(OrderPay $order,OrderService $orderService){
       // dd(11);


        if($order->paid_at){
            try{
                $result= $orderService->refundOrder($order);
            }catch (OrderServiceException $e){
                $error=    new MessageBag(
                    [
                        'title' => '失败',
                        'message' => $e->getMessage(),
                    ]);
                    return redirect()->back()->with(compact('error'));
            }
        }
        $success = new MessageBag(
            [
                'title' => '订单取消成功',
                'message' => '订单取消成功',
            ]
        );
        return redirect()->back()->with(compact('success'));
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(OrderPay::class, function (Form $form) {

            $form->display('id', 'ID');

            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }

}
